import React, {useCallback} from 'react';
import memo from '../common/wrapMemo';

import { message } from 'antd';
import api from '../../api';
import style from './AddUser.module.scss';
import { CloseOutlined } from '@ant-design/icons';
import RegisterForm from '../login/RegisterForm';

const AddUser = memo((props) => {
    const { onClose, onSuccess, userData, operationType } = props;

    const onFinish = useCallback((values) => {
        if(operationType === 'add'){
            api.user.register(values)
                .then((res) => {
                    const {code} = res.data;
                    if(code === 200) {
                        message.success('添加成功');
                        onSuccess();
                    }
                }).catch(err =>{
                    console.log(err);
                    message.error('添加失败');
                })
        }
        
        if(operationType === 'edit'){
            const {userId} = userData;
            values['userId'] = userId;
            api.user.updateUser(values)
                .then((res) => {
                    const {code} = res.data;
                    if(code === 200) {
                        message.success('保存成功');
                        onSuccess();
                    }
                }).catch(err =>{
                    console.log(err);
                    message.error('保存失败');
                })
        }
    },[operationType, userData]);

    return (
        <>
            <div className={style.addUser}>
                <div className={style.head}>
                    <span>{operationType === 'add' ? '添加' : '编辑'}</span>
                    <CloseOutlined onClick={onClose} />
                </div>
                <RegisterForm onFinish={onFinish} userData={userData} btnText="确定" />
            </div>
            <div className="mask"></div>
        </>
    );
});

export default AddUser;
